<script setup lang="ts">
import { mileageConversion, speedConvert } from '@/utils/gps/format'
import {h, nextTick, onMounted, onUnmounted, ref, watch} from 'vue'
import {type Column, ElTable, ElTooltip} from 'element-plus'
import { scrollToColumn } from '@/utils/gps/device'
import { gpsbus } from '@/utils/gps/event'
import { storeToRefs } from 'pinia'
import useDeviceStore from "@/store/gps/device";
import type { TableV2Instance } from 'element-plus'

const deviceStore = useDeviceStore()
const { checkedDeviceNodeId, checkedDeviceInfoList } = storeToRefs(deviceStore)

const tableRef = ref<TableV2Instance>()

watch(
  () => checkedDeviceNodeId.value,
  () => {
    setCurrentRow(checkedDeviceInfoList.value.findIndex(item => item.nodeId === checkedDeviceNodeId.value))
  }
)

// 行的配置
const columns: Column<any>[] = [
  {
    key: 'index', width: 60, title: '序号',
    cellRenderer: ({ rowIndex }) => h("span", `${rowIndex + 1}`),
    align: 'center'
  },
  {
    key: "plateNo", width: 180, title: "设备名称",
    dataKey: "plateNo",
    align: 'center'
  },
  {
    key: "imei", width: 180, title: "设备序列号",
    dataKey: "imei",
    align: 'center'
  },
  // {
  //   key: "name", width: 100, title: "总油量",
  //   dataKey: "direction",
  //   align: 'center'
  // },
  {
    key: "status",
    width: 80, title: "在线状态",
    dataKey: "connectionStatus",
    cellRenderer: ({cellData})=> h("span", cellData === 'online' ? '在线' : '离线'),
    align: 'center'
  },
  {
    key: "signalUpdateTime", width: 160, title: "最后更新",
    dataKey: "signalUpdateTime",
    align: 'center'
  },
  {
    key: "positionUpdateTime", width: 160, title: "有效定位",
    dataKey: "positionUpdateTime",
    align: 'center'
  },
  {
    key: "gotsrc", width: 100, title: "定位类型",
    dataKey: "gotsrc",
    align: 'center'
  },
  {
    key: "speed", width: 100, title: "速度",
    dataKey: "speed",
    cellRenderer: ({cellData})=> h("span", speedConvert(cellData)),
    align: 'center'
  },
  {
    key: "direction", width: 100, title: "方向",
    dataKey: "direction",
    align: 'center'
  },
  {
    key: "subTitle", width: 180, title: "状态",
    dataKey: "subTitle",
    align: 'center'
  },
  {
    key: "address", width: 300, title: "地址",
    dataKey: "address",
    cellRenderer: ({ cellData })=> h(ElTooltip,{
      effect: "dark",
      content: cellData,
      placement: "top"
    }, ()=> h("span", {
      style: "white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
    }, cellData)),
    // cellRenderer: ({ cellData })=> h("span", mileageConversion(cellData)),
    align: 'center'
  },
  {
    key: "voltage", width: 100, title: "电压",
    dataKey: "attribute",
    cellRenderer: ({cellData})=> h("span", cellData.power? cellData.power.toFixed(1) + "v" : 0),
    align: 'center'
  },
  {
    key: "satellite", width: 100, title: "卫星",
    dataKey: "attribute",
    cellRenderer: ({cellData})=> h("span", cellData.sat || 0),
    align: 'center'
  },
  {
    key: "mileageOfTheDay", width: 120, title: "当日里程",
    dataKey: "todayDistance",
    cellRenderer: ({cellData})=> h("span", mileageConversion(cellData)),
    align: 'center'
  },
  {
    key: "totalMileage", width: 140, title: "总里程",
    dataKey: "totalDistance",
    cellRenderer: ({cellData})=> h("span", mileageConversion(cellData)),
    align: 'center'
  },
]

const _height = ref(400)
const _width = ref(700)
let observer


onMounted(()=>{
  // 通过ResizeObserver 监听表格父级的宽高变化，动态设置表格宽高使得占满父级
  const div = document.querySelector("#checked_device_list")
  observer = new ResizeObserver((entries) => {
    entries.forEach((entry) => {
      // 限制最小宽度，避免造成布局混乱
      _width.value = entry.contentRect.width < 1200? 1200 : entry.contentRect.width
      _height.value = entry.contentRect.height
    })
  })
  observer.observe(div);
})

onUnmounted(()=>{
  const div = document.querySelector("#checked_device_list")
  observer.disconnect(div)
})

/**
 * 滚动到指定行
 * @param index
 */
function setCurrentRow(index: number){
  if(index < 0) return
  tableRef.value?.scrollToRow(index, "center")
}

/**
 * 给当前行设置选中样式， 以及给每一行设置悬浮样式
 * @param rowIndex
 */
function rowClass({ rowData }){
  if(rowData.nodeId === checkedDeviceNodeId.value) return "currentRow pointer"
  else return "pointer"
}

/**
 * 行的点击事件
 */
const rowHandler = {
  onClick({ rowData }) {
    gpsbus.emit("deviceSetRow", rowData.nodeId)
  },
}


</script>

<template>
  <div id="checked_device_list">
    <el-table-v2
        ref="tableRef"
        :columns="columns"
        :data="checkedDeviceInfoList"
        :width="_width"
        :height="_height"
        :header-height="30"
        :row-height="35"
        :row-class="rowClass"
        :fixed="true"
        :row-event-handlers="rowHandler"
    />
  </div>
</template>

<style scoped lang="scss">
.ellipsis{
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
::v-deep(.currentRow){
  background-color: rgb(204, 205, 206)!important;
}
::v-deep(.pointer){
  cursor: pointer;
}
</style>
